// pages/todo/todo.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    input:"",
    todos:[
      {content:"吃了吗",completed:false},
      {content:"有努力要加油",completed:true},
      {content:"越努力越幸运",completed:false},
      {content:"你只负责",completed:true},
      {content:"嘻嘻",completed:false}
    ],
    leftCount:2,
    allCompleted:false
  },
  // 拿到文本框里的值
  // 小程序的数据绑定是单向的，必须要给文本框绑定时间
  inputchangeHandle(e) {
    // console.log(e)
    // 设置input值为输入的value值
    this.setData({ input: e.detail.value })
  },
  // 点击时间触发回调函数,对todos数组添加数剧
  addToHandle() {
    if (!this.data.input) {
      return
    }
    var todos = this.data.todos;
    todos.push({
      content: this.data.input,
      completed: false
    })
    // 必须通过setData()去显示的改变，界面才会发生改变
    this.setData({
      todos: todos,
      input: "",
      leftCount: 1 + this.leftCount
    })
  },
  // 点击触发切换选中事件
  toggleTodoHandle(e) {
    // console.log(e)
    var item = this.data.todos[e.currentTarget.dataset.index]
    // 点击变为与之前相反的状态
    item.completed = !item.completed;
    var leftCount = this.data.leftCount + (item.completed ? -1 : 1)
    this.setData({
      todos: this.data.todos,
      leftCount: leftCount
    })
  },
  // 移除期中一项元素
  removeTodoHandle(e) {
    var todos = this.data.todos;
    var item = todos.splice(e.currentTarget.dataset.index, 1)[0]
    var leftCount = this.data.leftCount - (item.completed ? 0 : 1)
    this.setData({
      todos: todos,
      leftCount: leftCount
    })
  },
  toggleAllHandle() {
    //this在这里永远指向的是当前页面对象
    this.data.allCompleted = !this.data.allCompleted;
    var todos = this.data.todos;
    var that = this
    todos.forEach(function (item) {
      item.completed = that.data.allCompleted
    })

    var leftCount = this.data.allCompleted ? 0 : this.data.todos.length

    this.setData({
      todos: todos,
      leftCount: leftCount
    })

  },

  clearHandle() {

    var todos = []

    this.data.todos.forEach((item) => {
      if (!item.completed) {
        todos.push(item)
      }
    })

    // var todos = this.data.todos.filter(function(item){
    //   return !item.completed
    // })
    this.setData({
      todos: todos
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})